﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DeSleeper.Client.Properties;

namespace DeSleeper.Client
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : NavigationWindow
    {
		private static readonly Dictionary<Uri, object> _loadedPages = new Dictionary<Uri, object>();
        public MainWindow()
        {
            InitializeComponent();
			Loaded += loaded;
		}

		void loaded(object sender, RoutedEventArgs e)
		{
			NavigationService.Navigating += NavigationServiceNavigating;
			NavigationService.Navigated += NavigationServiceNavigated;
		}

		public static void NavigationServiceNavigated(object sender, NavigationEventArgs e)
		{
			if (e.Content != null && e.Uri != null)
				_loadedPages[e.Uri] = e.Content;
		}

    	public static void NavigationServiceNavigating(object sender, NavigatingCancelEventArgs e)
		{
			object alreadyLoadedPage;
    		if (e.Content != null || e.Uri == null || !_loadedPages.TryGetValue(e.Uri, out alreadyLoadedPage)) return;

    		e.Cancel = true;
    		var frame = e.Navigator as Frame;
    		var page = e.Navigator as Page;
    		var navigationWindow = e.Navigator as NavigationWindow;
    		if (frame != null)
    			frame.Navigate(alreadyLoadedPage);
    		if (page != null)
    			page.NavigationService.Navigate(alreadyLoadedPage);
    		if (navigationWindow != null)
    			navigationWindow.Navigate(alreadyLoadedPage);
		}

        private void mainWindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
			var focusedElement = Keyboard.FocusedElement as TextBox;
			if (focusedElement != null)
			{
				var expr = focusedElement.GetBindingExpression(TextBox.TextProperty);
				if (expr != null)
					expr.UpdateSource();
			}

			Settings.Default.Save();
        }
    }
}
